package tech.aistar.day11;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本类用来演示: 公平锁 - 非公平锁[默认的]
 *
 * @author: success
 * @date: 2022/8/2 1:45 下午
 */
@SuppressWarnings("all")
public class LockFairDemo {
    public static void main(String[] args) throws InterruptedException {
        //构建一个公平锁
        //公平锁 - 按照进入的顺序执行.先进来先执行
        //不公平锁 - cpu自己去调度,不是按照先来先执行的顺序.
        Lock lock = new ReentrantLock(true);

        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                //加锁
                try {
                    lock.lock();

                    TimeUnit.MILLISECONDS.sleep(20);

                    System.out.println(Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            },"t"+i).start();
        }
        //1s之后去争抢锁
        TimeUnit.SECONDS.sleep(1);

        for (int j = 0; j < 500; j++) {
            new Thread(()->{
                //加锁
                try {
                    lock.lock();

                    TimeUnit.MILLISECONDS.sleep(20);

                    System.out.println(Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            },"插队t"+j).start();
        }
    }
}
